package com.treasure.hunt.mine

import android.app.Activity
import android.content.Intent
import android.text.Editable
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.module.lemlin.LoadingDialog
import com.module.lemlin.mode.ViewModeActivity
import com.module.lemlin.rxhttp.Status
import com.module.lemlin.rxhttp.msg
import com.treasure.hunt.R
import com.treasure.hunt.mode.UserViewMode
import kotlinx.android.synthetic.main.activity_mine_info_update.*

class MineInfoUpdateActivity : ViewModeActivity<UserViewMode>() {

    companion object {

        private const val EXTRA_KEY_NICKNAME = "EXTRA_KEY_NICKNAME"

        fun open(activity: Activity, nickname: String?) {
            val intent: Intent = Intent(activity, MineInfoUpdateActivity::class.java).apply {
                putExtra(EXTRA_KEY_NICKNAME, nickname)
            }
            activity.startActivity(intent)
        }
    }

    override fun stateBar(): StatusBar {
        return StatusBar(
            isLightMode = false, bottomColor = R.color.FF_020027, view = flMineInfoUpdateBar
        )
    }

    override val layoutResId: Int
        get() = R.layout.activity_mine_info_update

    override fun viewModel(): UserViewMode {
        return createViewModel()
    }

    override fun initView() {
        intent?.getStringExtra(EXTRA_KEY_NICKNAME)?.let {
            etMineInfoUpdateNickname.text = Editable.Factory.getInstance().newEditable(it)
        }

        ivMineInfoUpdateBack.setOnClickListener {
            finish()
        }

        tvMineInfoUpdateSave.setOnClickListener {
            if (etMineInfoUpdateNickname.text.isNullOrEmpty()) {
                toast("请输入昵称")
            } else {
                viewModel.userProfile(etMineInfoUpdateNickname.text.toString())
            }
        }
    }

    override fun initViewMode() {
        viewModel.baseLiveData.observe(this as LifecycleOwner, Observer { response ->
            when (response.status) {
                Status.START -> LoadingDialog.show(this, R.layout.dialog_load_style_2)
                Status.FAILURE -> {
                    toast(response.throwable?.msg ?: "未知错误")
                    LoadingDialog.dismiss()
                }
                Status.SUCCESS -> {
                    LoadingDialog.dismiss()
                    finish()
                }
            }
        })
    }
}